/**
 * 用户首选项工具类
 */

import preferences from '@ohos.data.preferences';
import { Constants } from '../Constants';
import { Log } from '../Log';

class PreferenceUtil {
  preferences: preferences.Preferences = null;

  constructor() {}

  // 获取Preferences实例
  async getPreferencesFormStorage(context: any) {
    try {
      this.preferences = await preferences.getPreferences(context, Constants.PREFERENCES_NAME);
    } catch (err) {
      Log.error(Constants.LOG_TAG_NAME, `Failed to get preferences. Code: ${JSON.stringify(err)}`);
    }
  }

  // 从内存中移除指定的Preferences实例
  async deletePreferences(context: any) {
    try {
      await preferences.deletePreferences(context, Constants.LOG_TAG_NAME);
    } catch (err) {
      Log.error(Constants.LOG_TAG_NAME, `Failed to delete`)
    }
    this.preferences = null;
  }

  // 将数据写入Preferences实例
  async putPreference(context: any, key: string, value: string) {
    if (this.preferences === null) {
      await this.getPreferencesFormStorage(context);
    }
    try {
      await this.preferences.put(key, value);
    } catch (err) {
      Log.error(Constants.LOG_TAG_NAME, `Failed to put value, Cause: ${err}`);
    }
    // 实例持久化
    this.preferences.flush();
  }

  // 获取键对应的值
  async getPreference(context: any, key: string) {
    if (this.preferences === null) {
      await  this.getPreferencesFormStorage(context);
    }
    try {
      return <string> await this.preferences.get(key, '');
    } catch (err) {
      Log.error(Constants.LOG_TAG_NAME, `Failed to get value, Cause: ${err}`);
    }
  }
}

export default new PreferenceUtil();